<template>
  <div class="app-container">
    <div>
      <el-input v-model="newsViewModel.Title" size="small" placeholder="标题" style="width: 200px;" class="filter-item"
        @keyup.enter.native="queryNews" />
      <el-button type="primary" size="small" @click="queryNews" icon="el-icon-search">查询</el-button>
      <el-button type="primary" size="small" @click="handleAdd" icon="el-icon-plus">新增</el-button>
      <el-button type="primary" size="small" @click="refreshNews" icon="el-icon-refresh">刷新</el-button>
    </div>
    <el-table :data="newsList" v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      style="width: 100%;margin-top:30px;" border @sort-change="sortChange">
      <el-table-column label="项目名字" prop="Name">
        <template slot-scope="scope">{{ scope.row.Title }}</template>
      </el-table-column>
      <el-table-column label="描述" prop="Note" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.Note }}</template>
      </el-table-column>
      <el-table-column label="创建时间" prop="CreateTime">
        <template slot-scope="scope">{{ scope.row.CreateTime }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="oprateData(scope.row.ID)" icon="el-icon-document">资料</el-button>
          <el-button type="text" size="small" @click="handleEdit(scope)" icon="el-icon-edit">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope)" icon="el-icon-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件：https://element.eleme.cn/#/zh-CN/component/pagination -->
    <div class="block" style="float:right;margin-top:15px;" v-if="newsViewModel.total>0">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="newsViewModel.page" :page-sizes="[10, 20, 30, 40,100]" :page-size="newsViewModel.pageSize"
        @prev-click="lastPage" @next-click="nextPage" background layout="total, sizes, prev, pager, next, jumper"
        :total="newsViewModel.total"></el-pagination>
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑':'新增'" width="60%" top="2vh"
      :close-on-click-modal="false">
      <el-form :model="model" ref="model" :rules="rules" label-width="80px" label-position="right" style="width: 90%;">
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目名称" prop="Title">
              <el-input v-model="model.Title" placeholder="项目名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="Note">
              <el-input type="textarea" :rows="2" v-model="model.Note" placeholder="描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="授权" prop="RoleIdList">
              <el-select v-model="model.RoleIdList" multiple placeholder="请选择" style="width: 100%">
                <el-option v-for="item in roleList" :key="item.id" :label="item.label" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmModel">提交</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .v-modal {
    z-index: 2000 !important;
  }
</style>

<script>
  import { getProjectList, addModel, updateModel, deleteModel } from '@/api/project'
  import { deepClone } from "@/utils";
  import { getAllRoleListWithOptions } from '@/api/role'

  const defaultModel = {
    ID: '',
    Title: '',
    Note: '',
    Sort: '',
    IsShow: false,
    Mark: '',
    Creater: '',
    CreateTime: '',
    Modify: '',
    ModifyTime: ''
  }
  export default {
    data() {
      return {
        newsViewModel: {
          page: 1,
          pageSize: 10,
          total: 0,
          Title: '',
          OrderBy: 'CreateTime',//排序字段
          IsAsc: 'false', //是否升序
          SortDir: 'DESC'
        },
        randomNum: '',
        feditor: '',
        roleList: [],
        loading: false,
        upDialogFormVisible: false,
        dialogVisible: false,
        dialogType: '',
        model: Object.assign({}, defaultModel),
        newsList: [],
        newsTypeList: [],
        showList: [{ show: false, label: "否" }, { show: true, label: '是' }],
        apiPre: process.env.VUE_APP_BASE_API,
        actionUrl: '',
        StatesList: [
          { key: '-1', title: '全部' },
          { key: '0', title: '未发布' },
          { key: '1', title: '已发布' },
          { key: '2', title: '已下架' }
        ],
        rules: {
          Title: [
            { required: true, message: "请输入项目名字", trigger: "blur" },
            {
              min: 1,
              max: 100,
              message: "长度在 1 到 100 个字符",
              trigger: "blur"
            }
          ]
        }
      }
    },
    computed: { // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存

    },
    created() {  // 实例创建完成后执行的代码
      this.getNewsList(this.newsViewModel);
      this.actionUrl = this.apiPre + '/Upload/UploadFiles'
      this.getAllRoleList()
    },
    methods: {
      async getAllRoleList() {
        var res = await getAllRoleListWithOptions()
        if (res.code == 200)
          this.roleList = res.data
      },
      createEditor(content) {
        console.log(this.feditor)
        if (this.feditor) {
          if (content) {
            this.feditor.txt.html(content);
          }
          else {
            this.feditor.txt.html('');
          }
          return false
        }

        var editor = new wangeditor(this.$refs.editor);
        editor.customConfig.menus = [
          "head", // 标题
          "bold", // 粗体
          "fontSize", // 字号
          "fontName", // 字体
          "italic", // 斜体
          "underline", // 下划线
          "strikeThrough", // 删除线
          "foreColor", // 文字颜色
          "backColor", // 背景颜色
          "link", // 插入链接
          "list", // 列表
          "justify", // 对齐方式
          "quote", // 引用
          "image", // 插入图片
          'video',  // 插入视频
          "table", // 表格
          "undo", // 撤销
          "redo" // 重复
        ];
        editor.customConfig.zIndex = 2000;
        editor.customConfig.uploadImgServer =
          process.env.VUE_APP_BASE_API + "/Upload/UploadFiles";
        editor.customConfig.onchange = html => {
          this.model.Mark = html;
        };
        // 将图片大小限制为 3M
        editor.customConfig.uploadImgMaxSize = 5 * 1024 * 1024;
        editor.customConfig.uploadImgHooks = {
          success: function (xhr, editor, result) {
            // 图片上传并返回结果，图片插入成功之后触发
            // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
          },
          fail: function (xhr, editor, result) {
            // 图片上传并返回结果，但图片插入错误时触发
            // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
            this.$notify({
              title: "错误",
              type: "warning",
              message: "上传图片失败!"
            });
          },
          error: function (xhr, editor) {
            // 图片上传出错时触发
            // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
            this.$notify({
              title: "错误",
              type: "warning",
              message: "上传图片错误!"
            });
          },
          timeout: function (xhr, editor) {
            // 图片上传超时时触发
            // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
            this.$notify({
              title: "错误",
              type: "warning",
              message: "上传图片超时!"
            });
          },
          // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
          // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
          customInsert: function (insertImg, result, editor) {
            // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
            // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
            // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
            // window.console.log(result);
            var url = result.data;
            insertImg(url);
          }
        };
        editor.create();
        if (content) {
          editor.txt.html(content);
        }
        else {
          editor.txt.html('');
        }
        this.feditor = editor;
      },
      handleUpload() {
        this.randomNum = Math.random() * 997597 + ''
        this.upDialogFormVisible = true;
      },
      closeupDialog() {
        this.upDialogFormVisible = false;
        this.queryNews();
      },
      async getNewsList(newsViewModel) {
        this.loading = true
        const res = await getProjectList(newsViewModel);
        if (res.data) {
          this.newsViewModel.total = res.data.TotalCount;
        }
        this.newsList = res.data.Items;
        this.loading = false
      },
      async getAllNewsTypeList() {
        const res = await getAllNewsTypeList();
        this.newsTypeList = res.data
      },
      oprateData(id) {
        this.$router.push("/ems/projectData/" + id);
      },
      queryNews() {
        this.newsViewModel.page = 1
        this.getNewsList(this.newsViewModel);
      },
      refreshNews() {
        this.newsViewModel.Title = '';
        this.newsViewModel.SubTitle = '';
        this.newsViewModel.States = '-1';
        this.newsViewModel.page = 1
        this.getNewsList(this.newsViewModel);
      },
      sortChange(data) {
        const { prop, order } = data
        this.newsViewModel.OrderBy = prop
        if (prop == null || prop == "")
          this.newsViewModel.OrderBy = "UserID"
        if (order === 'ascending') {
          this.newsViewModel.IsAsc = true
        } else {
          this.newsViewModel.IsAsc = false
        }
        this.queryNews()
      },
      lastPage(val) {
        this.newsViewModel.page = val;
      },
      nextPage(val) {
        this.newsViewModel.page = val;
      },
      handleChange(value) {
        console.log(value);
      },
      handleSizeChange(val) {
        this.newsViewModel.pageSize = val;
        this.getNewsList(this.newsViewModel);
      },
      handleCurrentChange(val) {
        this.newsViewModel.page = val
        this.getNewsList(this.newsViewModel)
      },
      handlePublish(scope, status) {
        var str = "下架"
        if (status == 1)
          str = "上架"
        this.$confirm("确认" + str + scope.row.Title + "?", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            await publishModel(scope.row.Id, status);
            this.$notify({
              title: "成功",
              type: "success",
              message: "操作成功!"
            });
            this.queryNews()
          })
          .catch(err => {
            console.error(err);
          });
      },
      handleAdd() {
        this.dialogType = 'new';
        this.dialogVisible = true;
        this.model = deepClone(defaultModel)
        this.$nextTick(() => {
          this.$refs['model'].clearValidate() //清空上次的错误验证提示
        })

      },
      handleEdit(scope) {
        this.dialogType = 'edit';
        this.dialogVisible = true;
        this.model = Object.assign({}, scope.row);
        this.$nextTick(() => {
          this.$refs['model'].clearValidate() //清空上次的错误验证提示
        });
      },
      async confirmModel() {
        //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
        var v;
        this.$refs['model'].validate(valid => {
          v = valid;
        });
        if (!v) {
          return false;
        }
        const isEdit = this.dialogType === 'edit';
        var res
        if (isEdit) {
          res = await updateModel(this.model);
        } else {
          res = await addModel(this.model)
          this.newsViewModel.page = 1
        }
        if (res && !res.data) {
          this.$notify({
            title: "失败",
            type: "error",
            message: res.message
          });
          return
        }
        this.getNewsList(this.newsViewModel);
        this.model = deepClone(defaultModel)
        this.dialogVisible = false;
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      },
      handleDelete({ $index, row }) {
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            await deleteModel(row.ID);
            this.$notify({
              title: "成功",
              type: "success",
              message: "操作成功!"
            });
            this.getNewsList(this.newsViewModel);
          })
          .catch(err => {
            console.error(err);
          });
      },
      handleAvatarSuccess(res, file) {//图片上传成功响应方法
        this.model.ImageURL = res.data;
      },
      beforeAvatarUpload(file) {
        const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 4;

        if (!isImg) {
          this.$notify({
            title: "失败",
            message: "上传头像图片只能是 JPG/JPEG/PNG 格式!",
            type: "error",
            duration: 3000
          });
          return false
        }
        if (!isLt2M) {
          this.$notify({
            title: "失败",
            message: "上传头像图片大小不能超过 4MB!",
            type: "error",
            duration: 3000
          });
          return false
        }
        return true
      }
    }
  }
</script>